package com.example.cinema.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.example.cinema.BR;
import com.example.cinema.R;
import com.example.cinema.UserAttribute;
import com.example.cinema.adapter.CommentAdapter;
import com.example.cinema.bindingdata.MovieData;
import com.example.cinema.bindingdata.TypeGridData;
import com.example.cinema.bindingdata.VideoData;
import com.example.cinema.database.AppDataBase;
import com.example.cinema.database.DataBaseMethod;
import com.example.cinema.databinding.ActivityTypeBinding;
import com.example.cinema.request.RequestSend;
import com.example.cinema.request.RequestTypeList;
import com.example.cinema.testdara.TestData;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;

public class ActivityType extends AppCompatActivity {

    private ActivityTypeBinding ATB;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ATB = DataBindingUtil.setContentView(this, R.layout.activity_type);
        initradio();
        initListener();
        TypeGridData();
        ATB.grouptype.check(0);
        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = getWindow().getDecorView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }


    //初始化分类数据
    private DataBaseMethod db;
    private UserAttribute attribute;
    private List<MovieData> typedata;
    private void initradio() {
        attribute = (UserAttribute) getApplication();
        db = new DataBaseMethod(getApplicationContext(), "videotype");
        typedata = db.GetTypeData();
        int len = typedata.size();
        Log.i("LEB", len + "");
        for (int i = 0; i < len; i++) {
            MovieData mdata = typedata.get(i);
            if (mdata.typetags.equals("1024")) {
                continue;
            }
            RadioButton Rb = new RadioButton(getApplicationContext());
            Rb.setButtonDrawable(null);
            Rb.setText(mdata.typename);
            Rb.setTextColor(Color.parseColor("#939393"));
            Rb.setTextSize(14);
            Rb.setId(i-1);
            Rb.setTag(R.id.typeid, mdata.typetags);
            Rb.setPadding(30, 2, 30, 2);
            Rb.setBackgroundColor(Color.parseColor("#00000000"));
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            ATB.grouptype.addView(Rb);
        }


    }

    //Grid数据
    private CommentAdapter adapter;

    private void TypeGridData() {
        adapter = new CommentAdapter(getApplicationContext(), datalist, R.layout.type_grid_item, BR.videotatdatype);
        ATB.gridview.setAdapter(adapter);
    }

    //监听
    private String typeid;
    public boolean isscroll;
    private int cheid;

    private void initListener() {
        //分类选项监听
        ATB.grouptype.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Log.i("HHHH", checkedId + "--");
                datalist.clear();
                page = 1;
                TextView views = (TextView) group.getChildAt(checkedId);
                int ss = group.indexOfChild(views);
                TextView tvide = (TextView) group.getChildAt(ss);
                Log.i("HHHH","索引"+ss);
                int len = group.getChildCount();
                for (int i = 0; i < len; i++) {
                    TextView view = (RadioButton) group.getChildAt(i);
                    view.setTextSize(14);
                    view.setTextColor(Color.parseColor("#939393"));
                    TextPaint paint = view.getPaint();
                    paint.setFakeBoldText(false);
                }

                tvide.setTextColor(Color.parseColor("#FFFFFF"));
                tvide.setTextSize(16);
                TextPaint paint = views.getPaint();
                paint.setFakeBoldText(true);


                typeid = views.getTag(R.id.typeid).toString();

                Log.i("TTTT", typeid + "");
                ThreadTypeData();
            }
        });
        //返回
        ATB.finsh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //滚动监听
        ATB.gridview.setOnScrollListener(new AbsListView.OnScrollListener() {


            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == 0) {
                    isscroll = true;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int lens = firstVisibleItem + visibleItemCount;
                if (lens == totalItemCount) {
                    Log.i("RRRR", "到底");
                    if (isscroll) {
                        Log.i("RRRR", "执行滚动到底任务");
                        page++;
                        ThreadTypeData();

                    }
                }
            }
        });
        //列表点击监听
        ATB.gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (attribute.getUID() == null) {

                    Intent intent = new Intent();
                    intent.setAction("sign");
                    startActivity(intent);
                    return;
                }
                new Thread() {
                    @Override
                    public void run() {
                        RequestSend send = new RequestSend(getApplicationContext());
                        boolean b;
                        if(attribute.getAppMode()==0)
                        {
                            b = true;
                        }else {
                            b = send.VipCheck(attribute.getUID());
                        }
//                        if (b) {
                            Intent intent = new Intent();
                            intent.setAction("videoplayer");
                            Bundle bundle = new Bundle();
                            bundle.putString("title", datalist.get(position).videoname.get());
                            bundle.putString("vid", datalist.get(position).videosid.get());
                            bundle.putString("brief", datalist.get(position).videobrief.get());
                            bundle.putString("type", datalist.get(position).videotype.get());
                            bundle.putString("urls", datalist.get(position).videourls.get());
                            Log.i("AAAA", datalist.get(position).videourls.get());
                            bundle.putString("imglist", datalist.get(position).videoimge.get());
                            bundle.putString("uimg", datalist.get(position).videouimg.get());
                            bundle.putString("love", datalist.get(position).videolove.get());
                            bundle.putString("shorturl", datalist.get(position).videopart.get());
                            bundle.putBoolean("bool",b);
                            intent.putExtras(bundle);
                            startActivity(intent);
//                        } else {
//                            handler.sendEmptyMessage(1001);
//                        }
                    }
                }.start();


            }
        });
    }

    //提取数据
    private int page = 1;
    private int limit = 30;
    private List<VideoData> datalist = new ArrayList<>();

    private void ThreadTypeData() {
        new Thread() {
            @Override
            public void run() {
                Log.i("HHHD","执行");
                RequestTypeList rt = new RequestTypeList(getApplicationContext());
                boolean b = rt.GetVideo(String.valueOf(page), String.valueOf(limit), typeid, datalist);
                Message m = new Message();
                m.obj = b;
                m.what = 1000;
                handler.sendMessage(m);
                Log.i("HHHD","结束");
            }
        }.start();
    }


    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1000) {
                if (!(boolean) msg.obj) {
                    Toast.makeText(getApplicationContext(), "哎呀！没有更多影片了！", Toast.LENGTH_LONG).show();
                }

                adapter.notifyDataSetChanged();
                isscroll = false;
            }
            if (msg.what == 1001) {
                Dialog();

            }
        }
    };
    //非VIP提醒
    private AlertDialog alertDialog;

    private void Dialog() {
        int w = getResources().getDisplayMetrics().widthPixels;
        int h = getResources().getDisplayMetrics().heightPixels;
        View view = LinearLayout.inflate(getApplicationContext(), R.layout.dialog_item, null);

        LinearLayout.LayoutParams  paramsa = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        paramsa.width = w/5*2;
        paramsa.height= h/4*3;
        view.setLayoutParams(paramsa);
        int wi = getResources().getDisplayMetrics().widthPixels;
        alertDialog = new AlertDialog.Builder(ActivityType.this)
                .setView(view)
                .setCancelable(false)
                .show();
        Window window = alertDialog.getWindow();
        window.getDecorView().setPadding(0,0,0,0);
        window.getDecorView().setBackgroundColor(Color.argb(0, 0, 0, 0));
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = wi / 4 * 3;
        window.setAttributes(params);

        View vipview = view.findViewById(R.id.vipbtn);
        View wymf = view.findViewById(R.id.mfbtn);
        View close = view.findViewById(R.id.closebtn);
        vipview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳到VIP充值

                alertDialog.cancel();
                Intent intent = new Intent();
                intent.setAction("cartpay");
                startActivity(intent);
            }
        });
        wymf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳到推广分享

                alertDialog.cancel();
                Intent intent = new Intent();
                intent.setAction("spread");
                startActivity(intent);
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
    }

}
